package p6.code;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 车辆追踪器类
 * 在这个类中，它包含了Map,MutablePoint，且都是未发布的
 * 且关键方法都添加了内置锁
 * 所以可以认为这个类是线程安全的
 */
public class MonitorVehicleTracker {

    //声明位置合集
    private final Map<String ,MutablePoint> locations;

    //构造器，初始化位置合集
    public MonitorVehicleTracker(Map<String, MutablePoint> locations) {
        this.locations = deepCopy(locations);
    }

    //获得位置合集
    public synchronized Map<String,MutablePoint> getLocations() {
        return deepCopy(locations);
    }

    //获得指定车的位置对象
    public synchronized MutablePoint getLocation(String id){
        MutablePoint loc = locations.get(id);
        return loc == null ? null:new MutablePoint(loc);
    }

    //更新车的位置信息
    public synchronized void setLocations(String id,int x,int y) {
        MutablePoint loc = locations.get(id);
        if(loc==null)
            throw new IllegalArgumentException("No such ID: "+id);
        loc.x = x;
        loc.y = y;
    }

    //返回深拷贝位置合集
    private static Map<String,MutablePoint> deepCopy(Map<String,MutablePoint>m) {
        Map<String,MutablePoint> result=new HashMap<String,MutablePoint>();

        for(String id:m.keySet())
            result.put(id,new MutablePoint(m.get(id)));

        return Collections.unmodifiableMap(result);
    }

    /**
     * 位置类: 线程不安全
     */
     static class MutablePoint {

        public int x,y;

        public MutablePoint(){
            x=0;
            y=0;
        }
        public MutablePoint(MutablePoint p){
            this.x=p.x;
            this.y=p.y;
        }
    }

}



